package game;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class MainApp {

	/**
	 * @param args
	 */
	public static void run(String ip, String navn) throws Exception {
		game = Game.getInstance();
		game.initPlayerName(navn);
		game.run();
		Socket socket = new Socket(ip, 15676);
		if (!connect(socket)) {
			throw new Error("Couldn't connect to server!");
		}
		game.join();
	}

	public static boolean connect(Socket socket) throws IOException {

		BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		DataOutputStream out = new DataOutputStream(socket.getOutputStream());
		System.out.println("Sender connection request: 1#" + Game.getInstance().getPlayerName() + "\n");
		out.writeBytes("1#" + Game.getInstance().getPlayerName() + "\n");
		System.out.println("Har skrevet!\nLæser besked fra server:");

		String buffer = in.readLine();
		System.out.println("Besked: " + buffer);

		String[] information = buffer.split("#");
		System.out.println("TEST2");

		if (!information[0].equals("2")) {

		}

		System.out.println(information[1]);
		
		String color = information[2];

		setClient(new Client(Game.getInstance().getPlayerName(), socket, in, out));
		getClient().start();
		game.setPlayerColor(color);

		return true;
	}

	public static Client getClient() {
		return client;
	}

	public static void setClient(Client client) {
		MainApp.client = client;
	}

	private static Game game;
	private static Client client;

}
